package com.opesoft.fw.mvc.taglib;

import java.util.Collection;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.el.ExpressionEvaluator;

import org.apache.commons.beanutils.BeanUtils;

public class Options extends FormBase
{
	protected String items;
	protected String value;
	protected String text;
	protected String other;

	protected Select select;

	public int doStartTag() throws JspException
	{
		if(this.getParent()==null||!(this.getParent() instanceof Select)) throw new JspException("Options tag must have a parent tag as Select .");

		this.select=(Select)this.getParent();

		return super.doStartTag();
	}

	public int doEndTag() throws JspException
	{
		String html="";
		
		if(this.value==null) throw new JspException("Options tag's value property is required .");
		if(this.text==null) this.text=this.value;

		try
		{
			Object obj=this.pageContext.findAttribute(items);
			if(obj!=null&&obj instanceof Collection)
			{
				Collection coll=(Collection)obj;
				for(Object item : coll)
				{
					Object v=BeanUtils.getProperty(item,this.value);
					String vStr=v==null?"":v.toString();
					Object t=BeanUtils.getProperty(item,this.text);
					String tStr=t==null?"":t.toString();

					html+="<option";
					html+=this.htmlProprty("value",vStr);
					if(vStr.equals(select.value)) html+=" selected";

					if(this.other!=null) html+=other;
					html+=">"+tStr+"</option>\n";
				}
			}
		}
		catch(Exception e)
		{
			throw new JspException(e);
		}
		finally
		{
			this.write(html);
			this.select=null;
		}

		return super.doEndTag();
	}

	public String getOther()
	{
		return other;
	}

	public void setOther(String other)
	{
		this.other=other;
	}

	public String getValue()
	{
		return value;
	}

	public void setValue(String value)
	{
		this.value=value;
	}

	public String getItems()
	{
		return items;
	}

	public void setItems(String collection)
	{
		this.items=collection;
	}

	public Select getSelect()
	{
		return select;
	}

	public void setSelect(Select select)
	{
		this.select=select;
	}

	public String getText()
	{
		return text;
	}

	public void setText(String text)
	{
		this.text=text;
	}
}
